class Solution {
    public:
        vector<int> largestDivisibleSubset(vector<int>& nums) {
            int n = nums.size();
            vector<int> dp(n),last(n,-1);
            ranges::sort(nums);
            int a = 0;
            for(int i = 0;i < n;i++){
                for(int j = i + 1;j < n;j++){
                    if(nums[j] % nums[i] == 0 && dp[i] >= dp[j]){
                        dp[j] = max(1,dp[i] + 1);
                        last[j] = i;
                        if(dp[a] < dp[j]) a = j;
                    }
                }
            }
            vector<int> ans;
            while(a != -1){
                ans.push_back(nums[a]);
                a = last[a];
            }
            // ans.reverse();
            return ans;
        }
    };